package com.tarena.bo;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.tarena.util.HbnUtils;
import com.tarena.vo.Emp;

/**
 * 对数据库中员工表的操作类
 * 
 * @author Wangpeihu
 * @since 05/01/2010
 * @Team [Never give up]
 */
public class EmpDao {

	/**
	 * 增加一个新员工
	 * 
	 * @param emp
	 */
	public void addEmp(Emp emp) {
		Session s = HbnUtils.getSession();
		try {
			s.beginTransaction();
			s.save(emp);
			s.getTransaction().commit();
		} catch (HibernateException e) {
			s.getTransaction().rollback();
			throw new RuntimeException(e);
		} finally {
			s.close();
		}
	}

	/**
	 * 删除一个或多个员工
	 * 
	 * @param emp
	 */
	public void deleteEmp(int[] empId) {
		Session s = HbnUtils.getSession();
		try {
			s.beginTransaction();
			for (int i = 0; i < empId.length; i++) {
				s.delete(s.get(Emp.class, empId[i]));
			}
			s.getTransaction().commit();
		} catch (HibernateException e) {
			s.getTransaction().rollback();
			throw new RuntimeException(e);
		} finally {
			s.close();
		}
	}

	/**
	 * 查看是否拥有该名员工
	 * 
	 * @param emp
	 */
	public Emp findEmpById(Integer empId) {
		Session s = HbnUtils.getSession();
		Emp emp = (Emp) s.get(Emp.class, empId);
		s.close();
		return emp;
	}

	/**
	 * 更新一个员工
	 * 
	 * @param emp
	 */
	public void updateEmp(Emp emp) {
		Session s = HbnUtils.getSession();
		try {
			s.beginTransaction();
			s.update(emp);
			s.getTransaction().commit();
		} catch (HibernateException e) {
			s.getTransaction().rollback();
			throw new RuntimeException(e);
		} finally {
			s.close();
		}
	}

	/**
	 * 获得全部的员工信息
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Emp> findAllEmp() {
		Session s = HbnUtils.getSession();
		Query query = s.createQuery("from Emp e left outer join fetch e.dept");
		List<Emp> empList = query.list();
		s.close();
		return empList;
	}

}